<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\mysql\OeRebateMaterialModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class RebateMaterialService extends MediaService implements MediaInterface
{
    /**
     * 获取低质素材.
     *
     * @param string $agentId 代理商id
     * @param string $month 月份
     */
    public static function getRebateMaterial(string $agentId = '', string $month = ''): bool
    {
        try {
            $page = 0;
            $monthInt = intval(date('Ym', strtotime($month)));
            while (true) {
                $result = self::getList($agentId, $month, ++$page);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['materials']) == 0) {
                    break;
                }
                foreach ($result['data']['materials'] as $item) {
                    $model = self::getInfo($agentId, strval($item['advertiser_id']), $monthInt, strval($item['material_info']['material_id']));
                    if (! $model instanceof OeRebateMaterialModel || ! $model->getKey()) {
                        $model = new OeRebateMaterialModel();
                    }
                    $data = [
                        'agent_id' => $agentId,
                        'advertiser_id' => $item['advertiser_id'],
                        'material_id' => $item['material_info']['material_id'],
                        'material_create_time' => strtotime($item['material_info']['material_create_time']),
                        'material_month' => $monthInt,
                        'content' => json_encode($item, JSON_UNESCAPED_UNICODE),
                    ];
                    $model->setAttrs($data);
                    if (! $model->save()) {
                        throw new \Exception('保存信息出错');
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取低质素材.
     *
     * @param string $agentId 代理商id
     * @param string $month 月份
     * @param int $page 分页
     * @return bool|mixed|string
     */
    private static function getList(string $agentId = '', string $month = '', int $page = 0)
    {
        $advertiserId = (new ClientAccountModel())->where('media_id', CommonEnum::OE_MEDIA)
            ->where('agent_advertiser_id', '1689736213017623')->where('auth_valid', 1)->value('advertiser_id');
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'agent_id' => $agentId,
            'period' => $month,
            'filtering' => [
                'material_is_effective' => 1,
                'is_valid_video_material' => 2,
            ],
            'page' => $page,
            'page_size' => OceanEnum::MAX_PAGE_FIVE_SIZE,
        ];

        return AdvertiserService::getRebateMaterialList($headers, $params);
    }


    /**
     * 获取信息.
     *
     * @param string $agentId 代理商id
     * @param string $advertiserId 账户id
     * @param int $month 月份
     * @param string $materialId 素材ID
     * @return null|array|mixed|Model|OeRebateMaterialModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $agentId = '', string $advertiserId = '', int $month = 0, string $materialId = '')
    {
        $where = [
            ['agent_id', '=', $agentId],
            ['material_month', '=', $month],
            ['advertiser_id', '=', $advertiserId],
            ['material_id', '=', $materialId],
        ];

        return (new OeRebateMaterialModel())->where($where)->field(true)->find();
    }
}
